/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Utilities;

/**
 *
 * @author amendrashrestha
 */
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickMarkPosition;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.data.time.*;
import org.jfree.data.xy.XYDataset;

import javax.swing.*;
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;

public class BarChartScrollBarDemo extends JFrame {
    public BarChartScrollBarDemo() {
        super("BarChartScrollBarDemo");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateAxis domainAxis = new DateAxis("Date");
        NumberAxis rangeAxis = new NumberAxis("Volume");
        XYBarRenderer renderer = new XYBarRenderer(0.1);
        XYDataset dataset = getDataset();

        Day d1 = new Day();
        Day d2 = (Day) d1.next();
        domainAxis.setAutoRange(false);
        domainAxis.setRange(new DateRange(d1.getFirstMillisecond(), d2.getFirstMillisecond()));

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        mainPlot.setDomainGridlinesVisible(true);
        domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
        JFreeChart chart = new JFreeChart(null, null, mainPlot, true);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(600, 600));

        this.add(chartPanel);
        this.add(getScrollBar(domainAxis), BorderLayout.SOUTH);
        this.pack();
    }

    private XYDataset getDataset() {
        Hour h = new Hour();
        TimeSeries s1 = new TimeSeries("Series 1", Hour.class);
        for(int i=0 ; i<300 ; i++){
            h = (Hour) h.next();
            s1.add(h, Math.random() * 200);
        }
        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);

        return dataset;
    }

    private JScrollBar getScrollBar(final DateAxis domainAxis){
        final double r1 = domainAxis.getLowerBound();
        final double r2 = domainAxis.getUpperBound();
        JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 100, 0, 400);
        scrollBar.addAdjustmentListener( new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                double x = e.getValue() *60 *60 * 1000;
                domainAxis.setRange(r1+x, r2+x);
            }
        });
        return scrollBar;
    }

    public static void main(String[] args) {
        new BarChartScrollBarDemo().setVisible(true);
    }
}
